﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMasterPage.BLL;
using MvcMasterPage.Entity;
using Commons.Entity;
using System.Linq.Expressions;
using System.IO;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
namespace MvcMasterPage.Controllers
{
    /// <summary>
    /// 模块权限　
    /// </summary>
    public enum ModulePermissions
    {
        Logon = 1,
        History = 2,
        News = 4,
    }

    public class ServerMemory
    {

        public ServerMemory()
        {
            Initialize();
        }
        /// <summary>
        /// The lock used for synchronous
        /// </summary>
        private static readonly object _synlock = new object();

        /// <summary>
        /// Initializes container.
        /// </summary>
        public void Initialize()
        {
            if (HttpContext.Current.Application["role"] == null)
            {
                lock (_synlock)
                {
                    if (HttpContext.Current.Application["role"] == null)
                    {

                        HttpContext.Current.Application["role"] = 7;
                    }
                }
            }
        }

    }
    public class HomeController : BaseController
    {
        #region 向服务器模拟GET请求
        private static Dictionary<string, string> GetLanguages()
        {
            var url =
         "http://translate.googleapis.com" +
         "/translate_a/l?client=te&hl=zh-CN&cb=_callbacks_._0g3mb650r";

            var webClient = new WebClient();
            var script = webClient.DownloadString(url);
            var json = Regex.Match(script, @"({.+})}\)").Groups[1].Value;
            var serializer = new JavaScriptSerializer();
            return serializer.Deserialize<Dictionary<string, string>>(json);
        }

        private static string Translate(string source, string sl, string tl)
        {
            var url =
                       "https://translate.googleapis.com" +
                       "/translate_a/t?client=te&format=html&v=1.0";

            var data = String.Format(
                "q={0}&sl={1}&tl={2}&tc=1",
                HttpUtility.UrlEncode(source), sl, tl);

            var webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers.Add(
                HttpRequestHeader.UserAgent,
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0;)");

            var json = webClient.UploadString(url, data);
            var serializer = new JavaScriptSerializer();
            return serializer.Deserialize<string>(json);
        }
        #endregion
        UserManager userManager;
        public HomeController()
        {
            userManager = new UserManager();
        }

        /// <summary>
        /// 通过ＵＲＬ传输出来的categoryid
        /// </summary>
        /// <param name="categoryID"></param>
        /// <returns></returns>
        public ActionResult Index(int? menuID, string name, int? page)
        {

            ViewBag.Title = "主页~与母版页共用一个Action";
            ViewBag.MenuID = menuID;

            Expression<Func<User, bool>> predicate = null;
            if (!string.IsNullOrWhiteSpace(name))
                predicate = i => i.Name.Contains(name);
            //var model = userManager.GetUser(predicate, new PagingParam(page ?? 1, 3));
            var model = new PagedList<User>(new List<User> { }, page ?? 1, 3);
            if (Request.IsAjaxRequest())
                return PartialView("List", model);


            return View(model);
        }

        [HttpPost]
        public ActionResult Index()
        {
            return RedirectArtDialogToAction("ok", "Edit");
        }
        /// <summary>
        /// 关于我们
        /// </summary>
        /// <returns></returns>
        public ActionResult About()
        {

            return View();
        }
        /// <summary>
        /// 通过自身对象来得到categoryid
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int? id)
        {
            ViewBag.Title = "编辑页~与母版页共用一个Action";

            return View();
        }
        [HttpPost]
        public ActionResult Edit(FormCollection form)
        {

            User user = new User();
            // Deserialize (Include white list!)
            TryUpdateModel(user, new string[] { "UserName", "Email" }, form.ToValueProvider());

            // Validate
            if (String.IsNullOrEmpty(user.Name))
                ModelState.AddModelError("UserName", "UserName is required!");
            if (String.IsNullOrEmpty(user.Password))
                ModelState.AddModelError("Password", "Email is required!");

            // If valid, save movie to database
            if (ModelState.IsValid)
            {
                //DB Insert
                return RedirectToAction("Index");
            }
            return View(user);
        }

        public ActionResult LogOn(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            var logonMsg = "未登陆";
            HttpCookie cookie = HttpContext.Request.Cookies["eee114"];
            if (cookie != null)
            {
                if (cookie.HasKeys)
                {
                    logonMsg = "用户已经登陆";
                }
            }
            ViewBag.logonMsg = logonMsg;
            return View();
        }
        [HttpPost]
        public ActionResult LogOn(FormCollection form)
        {
            HttpCookie cookie = HttpContext.Request.Cookies["eee114"];
            if (cookie == null)
            {
                cookie = new HttpCookie("eee114") { Domain = "eee114.com" };
            }
            cookie["UserName"] = form["UserName"];
            HttpContext.Response.AppendCookie(cookie);

            if (!string.IsNullOrWhiteSpace(form["ReturnUrl"]))
                return Redirect(form["ReturnUrl"]);
            return RedirectToAction("Index", "Home");
        }
        public ActionResult LogOut(string returnUrl)
        {
            HttpCookie cookie = HttpContext.Request.Cookies["eee114"];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }
            if (!string.IsNullOrWhiteSpace(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction("Index", "Home");
        }
    }
}
